/**
 * $version:  0.1 
 * $Date: 2011-01-21 
 *
 * Copyright (C) 2010-2011 Jinrui Software. All rights reserved.
 *
 */

package org.jawa.admin.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jawa.core.util.JawaConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 验证用户是否登录。
 * <p>
 * 如果没有登录，则转向登录页面。
 * </p>
 * 
 * @author Y-N
 */
public class AuthCheckFilter implements Filter {
	
	private static final Logger Log = LoggerFactory
			.getLogger(AuthCheckFilter.class);

	// 系统登录页面
	private String loginPage;
	// 不进行过滤的页面
	private static Set<String> excludes = new HashSet<String>();
	// 系统是否使用了框架，默认是否
	private String useFrame;

	/**
	 * 初始化过滤器参数，包括系统的登录页面，不校验的页面等。
	 */
	public void init(FilterConfig config) throws ServletException {
		loginPage = config.getInitParameter("form-login-page");
		if (loginPage == null) {
			loginPage = "/login.jsp";
		}
		useFrame = config.getInitParameter("useFrame");
		if (useFrame == null) {
			useFrame = "false";
		}
		excludes.add(loginPage);
		String excludesProp = config.getInitParameter("excludes");
		if (excludesProp != null) {
			StringTokenizer tokenizer = new StringTokenizer(excludesProp, ";");
			while (tokenizer.hasMoreTokens()) {
				String tok = tokenizer.nextToken().trim();
				excludes.add(tok);
			}
		}
	}

	/**
	 * 对访问的页页进行登录过滤。
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();

		// 得到当前要访问的页面
		String url = request.getRequestURL().toString();

		// 看当前要访问的页面是否在排除列表中。如果在跳过过滤器
		boolean doExclude = false;
		for (String exclude : excludes) {
			if (url.indexOf(exclude) > -1) {
				doExclude = true;
				break;
			}
		}

		if (!doExclude) {
			Object user = session.getAttribute(JawaConstants.USER_KEY);
			if (user == null) {
				if (Boolean.valueOf(useFrame)) {
					String pstrScript = " <script type=\"text/javascript\"> ";
					pstrScript += "window.top.location= '"
							+ request.getContextPath() + loginPage + "'; ";
					pstrScript += " </script> ";
					response.getOutputStream().print(pstrScript);
				} else {
					response.sendRedirect(request.getContextPath() + loginPage);
				}
				return;
			}
		}
		chain.doFilter(req, res);
	}

	public void destroy() {
		excludes.clear();
	}

}
